﻿using Authentication.Model.Interface;
using Authentication.Model.Model;
using Common.Contract.Authentication.Record;
using Common.Contract.Authentication.Request;
using Common.Contract.Authentication.Response;
using Common.Contract.Paging;
using Common.Contract.SystemConfig.Record;
using Common.Service.Command;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Authentication.Core.ServiceCommand.ChangeDao
{
    public class RetrieveListChangeDaoRequestForSendMailServiceCommand : ProviderServiceCommand<IProviderFactory, RetrieveListChangeDaoRequestRequest, RetrieveListChangeDaoRequestResponse>
    {

        public int pageSize = 10, pageIndex = 0, totalRecord = 0;
        public string TextSearch;
        public FilterRecord Filter = null;
        private UserRecord currentUser;
        public RetrieveListChangeDaoRequestForSendMailServiceCommand(IProviderFactory providers) : base(providers) { }
        protected override void Validate(RetrieveListChangeDaoRequestRequest request)
        {
            if (request == null) throw new ArgumentNullException("request");
            if (!request.Header.ApplicationKey.HasValue || request.Header.ApplicationKey == Guid.Empty)
            {
                throw new ArgumentException("ApplicationKey must be set", "request");
            }
            if (request.CurrentUser == null)
            {
                throw new ArgumentException("User record must be set", "request");
            }
            else
            {
                currentUser = request.CurrentUser;
            }
            Filter = Request.Filter;
        }

        protected override bool OnExecute(RetrieveListChangeDaoRequestResponse response)
        {
            bool isSuccess = true;
            string errorMessage = string.Empty;
            int pageSize = 0, pageIndex = 0, totalRecord = 0;
            var applicationKey = Request.Header.ApplicationKey;
            try
            {
                if (Request.Page != null)
                {
                    pageIndex = Request.Page.PageIndex ?? 0;
                    pageSize = Request.Page.PageSize ?? 0;
                }
                List<ChangeDaoRequest> listChangRequest = new List<ChangeDaoRequest>();

                listChangRequest = Providers.ChangeDao.RetrieveListChangeDaoRequest(out totalRecord, currentUser, Filter, pageSize, pageIndex);
                List<int> listRequestId = listChangRequest.Select(x => x.Id).ToList();
                List<ChangeDaoCif> listChangeDaoCif = Providers.ChangeDao.RetrieveChangeDaoCif(currentUser, listRequestId);
                List<string> listChangeDaoCifCif = listChangeDaoCif.Select(x => x.Cif).ToList();
                List<ListDaoByRequest> listNewDaoCif = listChangeDaoCif == null ? new List<ListDaoByRequest>() : listChangeDaoCif.Select(x => new ListDaoByRequest
                {
                    RequestId = x.ChangeDaoId,
                    Dao = x.NewDao
                }).ToList();
                List<ChangeDaoProductChecked> listChangeDaoProduct = Providers.ChangeDao.RetrieveListChangeDaoProductByCifChecked(listChangeDaoCifCif, listRequestId);
                List<ListDaoByRequest> listDaoProduct = listChangeDaoProduct == null ? new List<ListDaoByRequest>() : listChangeDaoProduct.Select(x => new ListDaoByRequest
                {
                    RequestId = x.ChangeDaoRequestId.Value,
                    Dao = x.Dao
                }).ToList();
                List<Customers> listCustomer = Providers.Customer.RetrieveListCustomerByCif(listChangeDaoCifCif);
                var listAccount = Providers.Users.RetrieveAllUser().ToDictionary(x => x.Dao);

                List<ListDaoByRequest> listDaoCustomer = listCustomer == null ? new List<ListDaoByRequest>() : listCustomer.Join(listChangeDaoCif, x => x.Cif, y => y.Cif, (x, y) => new ListDaoByRequest { RequestId = y.ChangeDaoId, Dao = x.Dao }).ToList();

                //List<string> listDao = new List<string>();
                var listDao = listNewDaoCif.Concat(listDaoProduct).Concat(listDaoCustomer).GroupBy(x => x.RequestId).Select(x =>
                    new ListDaoByRequest
                    {
                        RequestId = x.Key,
                        ListDao = x.Where(y => listAccount.ContainsKey(y.Dao)).Select(y => listAccount[y.Dao].Email).Distinct().ToList()
                    }).ToDictionary(x => x.RequestId);

                if (listChangRequest == null)
                {
                    response.ErrorMessage = string.Format("Can not found user with Dao={0}", currentUser.Dao);
                    response.IsSuccess = false;
                }
                else
                {
                    List<ChangeDaoRequestRecord> records = listChangRequest.Select(x => new ChangeDaoRequestRecord
                    {
                        Id = x.Id,
                        Pic = x.Pic,
                        Reason = x.Reason,
                        Status = x.Status,
                        CreatedDate = x.CreatedDate,
                        ReasonDescription = x.ReasonDescription,
                        RejectReason = x.RejectReason,
                        RejectPerson = x.RejectPerson,
                        Zone = x.Branch.Region,
                        Branch = x.Branch.BranchNameSme,
                        IsDeviation = x.IsDeviation == 1,
                        ListDaoEmail = listDao[x.Id].ListDao
                    }).ToList();
                    response.Records = records;
                    response.Page = new PageRecord
                    {
                        PageIndex = pageIndex,
                        PageSize = pageSize,
                        TotalRecords = totalRecord,
                    };
                }
            }
            catch (Exception e)
            {
                Console.Write(e.Message);
                response.ErrorMessage = string.Format("Can not found user with Dao={0}", Request.CurrentUser.Dao);
                response.IsSuccess = false;
            }
            return isSuccess;
        }
        private class ListDaoByRequest
        {
            public int RequestId { get; set; }
            public string Dao { get; set; }
            public List<string> ListDao { get; set; }
        }
    }
}
